package com.shopping.controller;

import com.shopping.entity.MiaoshaOrder;
import com.shopping.entity.OrderInfo;
import com.shopping.entity.User;
import com.shopping.response.CodeMsg;
import com.shopping.service.GoodsService;
import com.shopping.service.MiaoshaService;
import com.shopping.service.OrderService;
import com.shopping.vo.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/miaosha")
public class MiaoshaController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private MiaoshaService miaoshaService;

    @RequestMapping("/do_miaosha")
    public String doMiaosha(long goodsId, Model model, User user){
        model.addAttribute("user",user);
        if(user==null){
            return "login";
        }

        //判断库存
        GoodsVO goodsVOByGoodsId = goodsService.getGoodsVOByGoodsId(goodsId);
        int stockCount=goodsVOByGoodsId.getStockCount();
        if(stockCount<=0){
            model.addAttribute("errormsg", CodeMsg.MIAO_SHA_ERROR.getMessage());
            return "miaosha_fail";
        }

        //判断是否已经秒杀掉了
       MiaoshaOrder miaoshaOrder= orderService.getMiaoshaOrderByOrderIdGoodsId(user.getId(),goodsId);
        if(miaoshaOrder!=null){
            model.addAttribute("errmessage",CodeMsg.REPEART_MIAOSHA.getMessage());
            return "miaosha_fail";
        }

        //减库存、下订单、写入秒杀订单
        OrderInfo orderInfo=miaoshaService.miaosha(user,goodsVOByGoodsId);
        model.addAttribute("orderInfo",orderInfo);
        model.addAttribute("goods",goodsVOByGoodsId);

        return "order_details";
    }
}
